package com.mxprojects.views
{
	import com.mxprojects.constructors.CheckboxConstructor;
	import com.mxprojects.constructors.InputConstructor;
	import com.mxprojects.constructors.PopupWindow;
	import com.mxprojects.gui.DefaultDialog;
	import com.mxprojects.gui.Emoticons;
	import com.mxprojects.gui.FileItem;
	import com.mxprojects.io.BoardCookie;
	import com.mxprojects.io.Config;
	import com.mxprojects.io.CustomEvent;
	import com.mxprojects.io.DeepLinking;
	import com.mxprojects.io.FileUploader;
	import com.mxprojects.io.ServerHandler;
	import com.mxprojects.language.Language;
	import com.mxprojects.language.Word;
	
	import flash.display.MovieClip;
	import flash.events.MouseEvent;
	import flash.net.FileReference;
	
	public class CreatePost
	{
		private static const INPUT_OFFSET_FROM_TOP:int = 50;
		private static const MINIMUM_CHARS:int = 3;
		private static const INPUT_CSS:String = "postCreateInput";
		private static const LABEL_CSS:String = "postCreateLabel";
		
		public static const ACTION_POST_NEW:String = "postNew";
		public static const ACTION_POST_REPLY:String = "postReply";
		
		private static const NEW_MESSAGE_ROW_HEIGHT:uint = 10;
		private static const REPLY_MESSAGE_ROW_HEIGHT:uint = 10;
		private static const MAXIMUM_SUBJECT_CHARS:int = 70; //this is set in the database, might want to figure out how to put it here as well
		
		private static var postPopup:PopupWindow = null;
		private static var messageInput:InputConstructor;
		private static var subscribeCheckbox:CheckboxConstructor;
		private static var postButton:MovieClip;
		private static var uploadButton:MovieClip;
		private static var uploader:FileUploader;
		private static var subjectInput:InputConstructor;
		private static var postForumID:int;
		private static var postThreadID:int;
		private static var postType:String;
		
		public static var serverHandler:ServerHandler = new ServerHandler();
		
		public function CreatePost(){}
		
		//create a new thread
		public static function create(actionType:String, forumID:int, forumTitle:String, threadID:int = -1, threadTitle:String = "", text:String = ""):void {
			//make it so they can't make more than 1 new thread
			if(postPopup == null){
				//setup a var to share with the other functions
				postForumID = forumID;
				postThreadID = threadID;
				postType = actionType;
				
				if(actionType == ACTION_POST_NEW){
					//create the popup
					postPopup = new PopupWindow(Config.CREATE_POST_POPUP_WIDTH, Config.CREATE_POST_POPUP_HEIGHT, Language.main(Word.NEW_THREAD), CreatePost.close);
					
					//add a little reminder to show what forum they are posting in
					postPopup.extraTitle(forumTitle);
					
					//add the inputs
					subjectInput = new InputConstructor(Language.main(Word.SUBJECT), "", 1, false, 1, LABEL_CSS, INPUT_CSS, MAXIMUM_SUBJECT_CHARS);
					subjectInput.x = Math.round(((postPopup.width - subjectInput.width) / 2) - (Config.TEXT_PADDING / 2));
					subjectInput.y = INPUT_OFFSET_FROM_TOP;
					
					messageInput = new InputConstructor(Language.main(Word.MESSAGE), text, 2, false, NEW_MESSAGE_ROW_HEIGHT, LABEL_CSS, INPUT_CSS);
					messageInput.x = Math.round(subjectInput.inputLabel.width - messageInput.inputLabel.width + subjectInput.x);
					messageInput.y = Math.round(subjectInput.y + subjectInput.height + Config.TEXT_PADDING/2);
					
					//add the subject box
					postPopup.addContent(subjectInput);
					postPopup.stage.focus = subjectInput.inputBox;
				}else{
					//create the popup
					postPopup = new PopupWindow(Config.CREATE_POST_POPUP_WIDTH, Config.CREATE_POST_POPUP_HEIGHT, Language.main(Word.POST_REPLY), CreatePost.close);
					
					//add a little reminder to show what thread they are posting in
					postPopup.extraTitle(threadTitle);
					
					//add the inputs
					messageInput = new InputConstructor(Language.main(Word.MESSAGE), text, 1, false, REPLY_MESSAGE_ROW_HEIGHT, LABEL_CSS, INPUT_CSS);
					messageInput.x = Math.round(((postPopup.width - messageInput.width) / 2) - (Config.TEXT_PADDING / 2));
					messageInput.y = INPUT_OFFSET_FROM_TOP;
					
					postPopup.stage.focus = messageInput.inputBox;
				}
				
				//add the stuff to the popup
				postPopup.addContent(messageInput);
				
				//allow them to subscribe to the thread
				subscribeCheckbox = new CheckboxConstructor(Language.main(Word.SUBSCRIBE_TO_THREAD_UPDATES), 
															Word.SUBSCRIBE_TO_THREAD_UPDATES, 
															Boolean(Config.POST_SUBSCRIBE_BY_DEFAULT));
				subscribeCheckbox.x = Math.round(messageInput.inputLabel.width + messageInput.x);
				subscribeCheckbox.y = messageInput.y + messageInput.height + Config.TEXT_PADDING/2;
				postPopup.addContent(subscribeCheckbox);
				
				//add the post button
				postButton = postPopup.createActionButton(Language.main(Word.SUBMIT_POST), submit);
				
				//setup the uploader
				uploader = new FileUploader(attachToPopup, true, Config.MAX_IMAGE_FILE_SIZE, Config.MAX_UPLOAD_FILES_POST, 
											Config.MAX_IMAGE_WIDTH, Config.MAX_IMAGE_HEIGHT, Config.POST_UPLOAD_SUB_DIRECTORY);
				
				//add an upload button
				uploadButton = postPopup.createActionButton(Language.main(Word.UPLOAD_IMAGES), uploader.setupUploadButton);
				
				//center the post and upload buttons
				postButton.x = Math.round(subscribeCheckbox.x + messageInput.inputBox.width/2 - (postButton.width + Config.TEXT_PADDING + uploadButton.width)/2);
				uploadButton.x = Math.round(postButton.x + postButton.width + Config.TEXT_PADDING);
			}else{
				//if there is any text sent to the popup, append it
				messageInput.inputBox.appendText(text);
			}

			messageInput.inputBox.setSelection(messageInput.inputBox.length, messageInput.inputBox.length);
		}
		
		private static function submit(event:MouseEvent):void {
			//this takes everything for the script to handle the submit
			var dataToSend:Object = new Object();
			var subject:String = "";
			if(subjectInput != null){
				subject = subjectInput.getValue();
			}
			var message:String = messageInput.getValue();
			
			if(postType == ACTION_POST_NEW){
				//check subject AND message
				if(subject.length < MINIMUM_CHARS || message.length < MINIMUM_CHARS){
					//throw an error about char count
					DefaultDialog.show(Language.main(Word.ERROR_NEW_POST) + " " + MINIMUM_CHARS, false);
					return;
				}
			}else{
				if(message.length < MINIMUM_CHARS){
					//throw an error about char count
					DefaultDialog.show(Language.main(Word.ERROR_REPLY_POST) + " " + MINIMUM_CHARS, false);
					return;
				}
			}
				
			//they are good with the message and subject, let's make sure they haven't spammed a billion emoticons
			if(Emoticons.count(message) < Emoticons.MAX_AMOUNT_PER_MESSAGE){
				//disable the post button
				postPopup.disableActionButton(postButton, submit);
				
				//get everything needed for the script
				dataToSend.subject = subject;
				dataToSend.message = message;
				dataToSend.username = BoardCookie.getUser();
				dataToSend.password = BoardCookie.getPassword();
				dataToSend.emoticons = 1;
				dataToSend.forumID = postForumID;
				dataToSend.threadID = postThreadID;
				dataToSend.isForumRestricted = Threads.isForumRestricted;
				dataToSend.postType = postType;
				dataToSend.postsPerPage = Config.POSTS_PER_PAGE;
				
				//subscribing?
				dataToSend.update = Language.main(Word.UPDATE);
				dataToSend.subscribe = subscribeCheckbox.getValueIfChecked();
				dataToSend.installDirectory = Config.INSTALL_DIRECTORY;
				dataToSend.replyMessage = Language.main(Word.MESSAGE_NEW_REPLY);
				dataToSend.boardName = Config.BOARD_NAME;
				dataToSend.boardEmail = Config.BOARD_EMAIL;
				
				//add any images
				dataToSend.uploadImageCount = uploader.totalFilesSelected;
				for(var i:int = 0; i < uploader.totalFilesSelected; i++){
					var fileItem:FileItem = postPopup.getContent("file"+i) as FileItem;
					dataToSend["file" + i] = fileItem.getFileName();
					dataToSend["file" + i + "Description"] = fileItem.getDescription();
				}
				
				//send it all off
				serverHandler.transmitData("createpost.php", dataToSend);
				
				//after the post is made, head to it
				serverHandler.listenForData(loadPost);
			}else{
				DefaultDialog.show(Language.main(Word.ERROR_EMOTICON_AMOUNT) + " " + Emoticons.MAX_AMOUNT_PER_MESSAGE, false);
			}
		}
		
		protected static function attachToPopup(file:FileReference, selectedNumber:int, showProgress:Boolean):void {			
			//process the upload file and add the UI to the popup
			var fileItem:FileItem = new FileItem(file, uploader, messageInput.inputBox.width, Config.POST_UPLOAD_SUB_DIRECTORY, showProgress);
			fileItem.x = messageInput.x + messageInput.inputLabel.width;
			fileItem.y = subscribeCheckbox.y + subscribeCheckbox.height + Config.TEXT_PADDING + (uploader.totalFilesSelected * fileItem.height);
			postPopup.addContent(fileItem, postButton, uploadButton);
			
			//listen for when it's done uploading
			fileItem.addEventListener(FileItem.ADDED_FILE, placeOnPopup, false, 0, true);
			fileItem.addEventListener(FileItem.REMOVED_FILE, removeFromPopup, false, 0, true);
		}
		
		private static function placeOnPopup(event:CustomEvent):void {
			//once it's done uploading, position it
			var fileItem:FileItem = event.target as FileItem;
			fileItem.x = messageInput.x + messageInput.inputLabel.width;
			fileItem.y = subscribeCheckbox.y + subscribeCheckbox.height + Config.TEXT_PADDING + (fileItem.getID() * fileItem.height);
			postPopup.changeHeight(postPopup.height + fileItem.height);
		}
		
		private static function removeFromPopup(event:CustomEvent):void {
			//resize the popup
			var fileItem:FileItem = event.target as FileItem;
			postPopup.changeHeight(postPopup.height - fileItem.height);
		}
		
		protected static function loadPost(event:CustomEvent):void {
			//re-enable the post button
			postPopup.enableActionButton(postButton, submit);
			
			//this will load the new thread or reply right after the post was made
			var serverData:Object = event.getServerData();
			
			switch(serverData.output){
				case "badLogin":
					DefaultDialog.show(Language.main(Word.ERROR_LOGIN_INVALID), false);
				break;
				
				case "mySqlError":
					DefaultDialog.show(Language.main(Word.ERROR_MYSQL) + "<br>" + serverData.error, false);
				break;
				
				case "generalError":
					DefaultDialog.show(Language.main(Word.ERROR) + "<br>" + serverData.error, false);
				break;
				
				case "success":
					//if we are in the same spot let's make sure we force a refresh
					if(DeepLinking.getQueryString() == "t=" + serverData.threadID + "&p=" + serverData.page){
						//force a refresh
						Posts.load(serverData.threadID, serverData.page);
					}else{
						//otherwise go where we need to
						DeepLinking.setLink(Word.POSTS, DeepLinking.createLinkArray(serverData.threadID, serverData.page));
					}
					
					//close the popup without deleting the uploaded files
					close(new MouseEvent("CLEAN_CLOSE"));
				break;
			}
		}
		
		protected static function close(event:MouseEvent):void {
			if(postPopup != null){
				if(event.type != "CLEAN_CLOSE"){
					//delete any files that were uploaded to the thread
					for(var i:int = 0; i < uploader.totalFilesSelected; i++){
						//remove any images that are no longer of use
						var fileItem:FileItem = postPopup.getContent("file"+i) as FileItem;
						fileItem.removeFile(event);
					}
				}
				postPopup.removeFromStage();
				postPopup = null;
			}
		}

	}
}